<template>
  <div class="container">
    <div class="main-content">
      <div style="text-align: end">
        <a-space>
          <a-button type="primary" style="display: none">新增项目</a-button>
          <a-button type="primary" status="danger" style="display: none">删除 </a-button>
          <a-button type="primary" @click="data.showModal = true">镜像导入 </a-button>
          <a-button type="primary" style="display: none">镜像导出</a-button>
        </a-space>
      </div>
      <a-divider :margin="10" />
      <a-table :data="data.tableData" :pagination="false">
        <template #columns>
          <a-table-column title="序号">
            <template #cell="{ rowIndex }">{{ rowIndex + 1 }}</template>
          </a-table-column>
          <a-table-column title="项目名称" data-index="projectName" />
          <a-table-column title="名称" data-index="name" />
          <a-table-column title="镜像名称" data-index="imageName" />
          <a-table-column title="仓库地址" data-index="repository" />
          <a-table-column title="标签" data-index="tag" />
          <a-table-column title="创建时间" data-index="createTime" />
          <a-table-column title="操作">
            <template #cell="{ record }">
              <a-button type="text" @click="data.showModal = true" style="display: none" size="small">
                <template #icon>
                  <icon-plus />
                </template>
                新增容器
              </a-button>
              <a-button type="text" status="success" size="small" @click="containerManage.openModal(record)">
                <template #icon>
                  <i class="bi bi-bar-chart-steps"></i>
                </template>
                服务运行管理
              </a-button>
              <a-button type="text" status="danger" size="small" @click="handleDelete(record)">
                <template #icon>
                  <icon-delete />
                </template>
                删除
              </a-button>
              <a-button type="text" status="normal" size="small" @click="exportImage(record)">
                <template #icon>
                  <icon-export />
                </template>
                导出
              </a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>
      <a-modal
        v-if="containerManage.image"
        width="900px"
        v-model:visible="containerManage.showModal"
        :footer="false"
        draggable
      >
        <template #title>
          <div class="flex flex-row justify-between">
            <div class="text-[16px] font-bold"><icon-list /> &nbsp;服务运行管理</div>
          </div>
        </template>
        <div class="pb-[10px] flex justify-between">
          <span>
            <a-typography-paragraph copyable :copy-text="containerManage.image.name">
              镜像名称：
              <a-tag class="!font-bold" size="large" color="blue">
                {{ containerManage.image.name }}
              </a-tag>
              <template #copy-icon>
                <a-tag class="!font-bold" size="large" color="blue">
                  <icon-copy />
                </a-tag>
              </template>
            </a-typography-paragraph>
          </span>

          <a-button
            size="small"
            type="primary"
            @click="
              () => {
                containerManage.showConfirmModal = true
                containerManage.subForm = {
                  containerName: '',
                  deploymentName: '',
                  imagesUrl: containerManage.image.repository,
                  nodePort: null,
                  reCreate: false
                }
              }
            "
          >
            <template #icon>
              <icon-plus />
            </template>
            创建新服务
          </a-button>

          <a-modal
            v-model:visible="containerManage.showConfirmModal"
            @ok="containerManage.handleCreate(containerManage.subForm)"
          >
            <template #title>
              <div class="text-[16px] font-bold"><icon-list /> &nbsp;服务运行管理</div>
            </template>
            <a-form :model="containerManage.subForm">
              <a-form-item label="镜像地址">
                <a-tag>{{ containerManage.subForm.imagesUrl }}</a-tag>
              </a-form-item>
              <a-form-item label="端口" field="nodePort" :rules="[{ required: true, message: '请输入端口' }]">
                <a-input-number
                  :min="3000"
                  :max="66000"
                  v-model="containerManage.subForm.nodePort"
                  placeholder="请输入端口"
                />
              </a-form-item>
            </a-form>
          </a-modal>
        </div>
        <a-table
          :loading="containerManage.table.loading"
          :data="containerManage.table.data"
          :pagination="false"
          :scroll="{
            x: '100%',
            maxHeight: '500px'
          }"
        >
          <template #columns>
            <a-table-column title="ID" data-index="id">
              <template #title>
                <div class="text-center">ID</div>
              </template>
            </a-table-column>
            <a-table-column title="服务名称" data-index="name">
              <template #title>
                <div class="text-center">
                  <icon-scan />
                  服务名称
                </div>
              </template>
            </a-table-column>
            <a-table-column title="端口" data-index="ports">
              <template #title>
                <div class="text-center"><i class="bi bi-plugin"></i> 端口</div>
              </template>
            </a-table-column>
            <a-table-column title="运行状态" data-index="status">
              <template #title>
                <div class="text-center"><i class="bi bi-bar-chart-steps"></i> 运行状态</div>
              </template>
              <template #cell="{ record }">
                <a-tag v-if="record.status === 'running'" color="green">运行中</a-tag>
                <a-tag v-if="record.status === 'exited'" color="red">已停止</a-tag>
              </template>
            </a-table-column>
            <a-table-column title="" data-index="op" width="300">
              <template #title>
                <div class="text-center w-[200px]">
                  <icon-settings />
                  运行操作
                </div>
              </template>
              <template #cell="{ record }">
                <a-button
                  type="text"
                  :disabled="record.status === 'running'"
                  status="success"
                  @click="containerManage.handleRestart(record)"
                >
                  <template #icon>
                    <icon-play-arrow />
                  </template>
                  重新创建
                </a-button>
                <a-button
                  :disabled="record.status === 'running'"
                  type="text"
                  status="danger"
                  @click="containerManage.handleDeleteContainer(record)"
                >
                  <template #icon>
                    <icon-delete />
                  </template>
                  删除
                </a-button>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </a-modal>
      <a-pagination
        class="my-1"
        style="float: right; margin-right: 20px; margin-top: 20px; justify-content: end"
        :total="data.total"
        :current="data.paginationData.pageStart"
        :page-size="data.paginationData.pageLength"
        show-total
        show-jumper
        show-page-size
        @change="handleCurrentChange"
        @page-size-change="handleSizeChange"
      />
      <a-modal
        v-model:visible="data.showModal"
        title="镜像导入"
        class="modelCont"
        width="600px"
        @before-ok="handleOk"
        @before-cancel="handleCancel"
      >
        <a-form ref="formRef" :model="data.form">
          <a-form-item label="镜像名称" field="imageName" :rules="[{ required: true, message: '请输入镜像名称' }]">
            <a-input v-model="data.form.imageName" />
          </a-form-item>
          <a-form-item label="镜像标签" field="tag" :rules="[{ required: true, message: '请输入镜像名称' }]">
            <a-input v-model="data.form.tag" />
          </a-form-item>
          <a-form-item label="文件上传" field="filePath">
            <a-upload :limit="1" :custom-request="handleUpload" :show-file-list="true" :file-list="fileList" />
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </div>
</template>

<script setup>
import { Modal, Message } from '@arco-design/web-vue'
import { ref, reactive, onMounted } from 'vue'
import { apiTemplate } from '@/api/complexModel'
import { apiContainer } from '@/api/container'

const FORM = {
  imageName: '',
  tag: '',
  filePath: ''
}
const containerManage = reactive({
  showModal: false,
  subForm: {
    containerName: '',
    deploymentName: '',
    imagesUrl: '',
    nodePort: 0,
    reCreate: false
  },
  table: {
    loading: false,
    data: [],
    pagination: {
      pageStart: 1,
      pageLength: 10
    }
  },
  image: null,
  showConfirmModal: false,
  handleDeleteContainer: (record) => {
    Modal.confirm({
      title: '删除',
      content: `确定删除${record.name}容器吗？`,
      onOk: () => {
        const loading = Message.loading({
          content: '删中...',
          duration: 0
        })
        apiContainer
          .deleteContainer({ id: record.id })
          .then((res) => {
            Message.success('删除成功')
            if (res.code === 200) {
              Message.success('删除成功')
            } else {
              Message.error(res.message)
            }
          })
          .catch((err) => {
            Message.error(err.message)
          })
          .finally(() => {
            loading.close()
          })
      }
    })
  },
  handleRestart: (record) => {
    const loading = Message.loading({
      content: '启动中...',
      duration: 0
    })
    apiContainer
      .startContainer({ id: record.id })
      .then((res) => {
        Message.success('启动成功')
        if (res.code === 200) {
          Message.success('启动成功')
          containerManage.loadData()
        } else {
          Message.error(res.message)
        }
      })
      .catch((err) => {
        Message.error(err.message)
      })
      .finally(() => {
        loading.close()
      })
  },
  handleCreate: (data) => {
    if (!containerManage.subForm.nodePort) {
      Message.error('缺少端口号')
      return
    }
    const loading = Message.loading({
      content: '创建中...',
      duration: 0
    })
    apiContainer
      .runContainer(data)
      .then((res) => {
        if (res.code === 200) {
          Message.success('创建成功')
          containerManage.loadData()
        } else {
          Message.error(res.message)
        }
      })
      .catch((err) => {
        Message.error(err.message)
      })
      .finally(() => {
        loading.close()
      })
  },
  loadData: () => {
    containerManage.table.loading = true
    apiContainer
      .getContainerList()
      .then((res) => {
        if (res.code === 200) {
          containerManage.table.data = res.data
        } else {
          Message.error(res.message)
        }
      })
      .catch((err) => {
        Message.error(err.message)
      })
      .finally(() => {
        containerManage.table.loading = false
      })
  },
  openModal: (image) => {
    containerManage.image = image
    containerManage.showModal = true
    containerManage.loadData()
  }
})
const data = reactive({
  showModal: false,

  tableData: [
    {
      id: 1,
      name: '54duijie',
      level: '公开',
      role: '项目管理员',
      number: '0',
      chart: '0',
      createTime: '2024-10-08 10:00:00'
    },
    {
      id: 2,
      name: 'algorithm',
      level: '公开',
      role: '项目管理员',
      number: '0',
      chart: '0',
      createTime: '2024-10-08 10:00:00'
    },
    {
      id: 3,
      name: 'big-spectrum',
      level: '公开',
      role: '项目管理员',
      number: '6',
      chart: '0',
      createTime: '2024-10-08 10:00:00'
    }
  ],
  form: { ...FORM },
  total: 0,
  paginationData: {
    pageStart: 1,
    pageLength: 10
  }
})

const fileList = ref([])
const formRef = ref(null)
const handleOk = (done) => {
  formRef.value.validate().then((col) => {
    if (!col) {
      apiTemplate
        .saveImage(data.form)
        .then((res) => {
          if (+res.code === 200) {
            done()
            Message.success('保存成功')
            data.showModal = false
            data.form = { ...FORM }
            fileList.value = []
          } else {
            done(false)
          }
        })
        .finally(() => {
          done(false)
        })
    } else {
      done(false)
    }
  })
}

const handleCancel = () => {
  formRef.value.resetFields()
  data.form = { ...FORM }
  fileList.value = []
  data.showModal = false
}

const handleUpload = (options) => {
  const { fileItem, onSuccess, onError } = options
  const params = {
    file: fileItem.file
  }
  console.log(params)
  apiTemplate
    .uploadImage(params)
    .then((res) => {
      if (+res.code === 200) {
        Message.success('上传成功')
        fileList.value = [
          {
            uid: new Date().getTime(),
            name: fileItem.file.name,
            url: res.data
          }
        ]
        data.form.filePath = res.data
        onSuccess()
      }
    })
    .catch(() => {
      onError()
    })
}

const handleDelete = (record) => {
  Modal.confirm({
    title: '删除',
    content: `确定要删除${record.name}吗？`,
    okText: '确定',
    cancelText: '取消',
    onOk: () => {
      // data.tableData = data.tableData.filter((item) => item.id !== record.id);
      apiTemplate.deleteImage(record.imageName).then((res) => {
        if (+res.code === 200) {
          Message.success('删除成功')
          getList()
        }
      })
    }
  })
}
const handleRun = (record) => {
  Modal.confirm({
    title: '创建容器',
    content: `确定要基于镜像${record.name}创建容器吗？`,
    okText: '确定',
    cancelText: '取消',
    onOk: () => {
      // data.tableData = data.tableData.filter((item) => item.id !== record.id);
      apiTemplate.deleteImage(record.imageName).then((res) => {
        if (+res.code === 200) {
          Message.success('创建容器成功')
          getList()
        }
      })
    }
  })
}
const exportImage = (record) => {
  Modal.confirm({
    title: '导出',
    content: `确定要导出${record.name}吗？`,
    okText: '确定',
    cancelText: '取消',
    onOk: () => {
      if (import.meta.env.MODE === 'development') {
        console.log(
          `http://172.17.10.76:8084/complex-model-back/complex-model-back/v1.0/image/download?imageName=${record.name}&repository=${record.repository}`
        )
        window.open(
          `http://172.17.10.76:8084/complex-model-back/complex-model-back/v1.0/image/download?imageName=${record.name}&repository=${record.repository}`,
          '_blank'
        )
      } else {
        window.open(
          `/complex-model-back/complex-model-back/v1.0/image/download?imageName=${record.name}&repository=${record.repository}`,
          '_blank'
        )
      }
    }
  })
}

const getList = () => {
  apiTemplate.getImageList().then((res) => {
    if (+res.code === 200) {
      data.tableData = res.data.rows
      data.total = +res.data.total
    }
  })
}

const handleCurrentChange = (val) => {
  data.paginationData.pageStart = val
  getList()
}
const handleSizeChange = (val) => {
  data.paginationData.pageLength = val
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style lang="less" scoped>
.lookBtn {
  color: #1d68d0;
}

.modelCont {
  width: 860px;
}

.btnBox {
  display: flex;

  div {
    margin-right: 10px;
    cursor: pointer;
  }
}

.container {
  display: flex;
  min-height: calc(100vh - 56px);
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
}
</style>
